using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.IO;

namespace CodePlex.EnterpriseFramework
{
    public class XmlHelper
    {
        /// <summary>
        /// Validate XML instance againest xsd schema
        /// </summary>
        /// <param name="instance">Data in</param>
        /// <param name="schemaPath">Schema physical path</param>
        /// <param name="schemaNamespace">Namespace</param>
        public static XmlDocument ProcessInstance(XmlDocument instance)
        {
            XmlDocument xmlOutDoc = null;

            try
            {
                string schemaNamespace = instance.DocumentElement.NamespaceURI;
                string schemaPath = ConfigurationManager.SchemaFolderPath + schemaNamespace.Substring(7) + ".xsd";

                Stream instanseStream = new System.IO.MemoryStream();
                instance.Save(instanseStream);
                instanseStream.Position = 0;

                XmlReaderSettings settings = new XmlReaderSettings();
                settings.Schemas.Add(schemaNamespace, schemaPath);
                settings.ValidationType = ValidationType.Schema;

                XmlReader reader = XmlReader.Create(instanseStream, settings);                

                ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);

                // Check Instance
                while (reader.Read()) ;

               // Get Transform File
               XmlNode mapNode = instance.SelectSingleNode("/*/Map");

               if (null != mapNode && "" != mapNode.InnerText)
               {
                   instanseStream.Position = 0;
                   XmlReader instanceReader = XmlReader.Create(instanseStream);
                   Stream outputStream = Common.XmlTransform(ConfigurationManager.MapFolderPath + mapNode.InnerText, instanceReader);

                   xmlOutDoc = new XmlDocument();
                   outputStream.Position = 0;
                   xmlOutDoc.Load(outputStream);
               }
               if (null == xmlOutDoc) throw new Exception("Transformation Error, Please ");
                return xmlOutDoc;
            }
            catch (Exception e)
            {
                // Error Logging
                System.Diagnostics.EventLog.WriteEntry("SharePoint List Updater", e.ToString());
                throw (e);
            }
        }

        /// <summary>
        /// This event handler is used internally by ValidateXmlInstance
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Error</param>
        private static void ValidationEventHandler(object sender, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Error)
            {
                throw new System.Xml.XmlException(e.Message);
            }
        }
    }
}
